/*
NAME:
DESCRIPTION: ;
PARAMETER:
    [
        {
            name: 'step_filter',
            title: 'step过滤',
            type: 'LineEdit'
        },
        {
            name : 'auto_save',
            title : '自动保存',
            type : 'RadioBox',
            property : {
                item_list:[
                    {name:'yes',text:'YES'},
                    {name:'no',text:'NO'},
                ],
                tool_tip:'是否自动保存料号开关'
            }
        }
    ]
    
 VERSION_HISTORY:
    V1.00 2020-09-28 Scott
        1.新版本
        
 HELP:
    <html><body bgcolor="#DDECFE">
        <font size="3" color="#003DB2"><p>功能简介</p></font>
        <p> 钻孔补偿 </p>
        <br>
        <font size="3" color="#003DB2"><p>参数配置</p></font>
        <p> </p>
        <br>
        <font size="3" color="#003DB2"><p>注意事项</p></font>
        <p> 无 </p>
        <br>
    </body></html>
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("=============================>JTG_DRL_compensation_aim");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm;
if (IKM == undefined) {
    IKM = require('topcam.ikm6')($);
}
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db;
var PAR = {};
if ($.par) {
    PAR = $.par;
}
else if ($.hasOwnProperty('script_parameter')) {
    PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
    var database = require("topsin.database");
    database.addConnection($.conf.database_conf, "DFM");
    var QDfm = database.query("DFM");
    $.QDfm = QDfm;
    if ($.conf.product_type == "aimdfm") {
        QDfm.updateRow({
            table: "pdm_aimdfm_task",
            data: {
                current_process_title: $.process_title
            },
            where: { id: $.task_id }
        });
    }
}
var Status = 'ok';
var resultData = [];
// 表面处理数据
var surfaceValue = IKM.get_jobinfo({ jobid: JobId, jobinfo: 'surface_treatment' });
var jtg_through_hole_treatment = IKM.get_jobinfo({ jobid: JobId, jobinfo: 'jtg_through_hole_treatment' });  // 过孔




// 压接孔数据(注意拆分形式; 注意单位换算 mm=>um)
// var crimpHole = IKM.get_jobinfo({ jobid: JobId, jobinfo: 'jtg_special_tolerance_hole_diameter_final' });
try {
    var par = PAR;
    var default_par = {
        step_filter: 'unit.+',
        step2:"unit",
        auto_save: "No",
        units: 'mm'
    };
    for (var key in default_par) { // 设置默认属性
        if (!par.hasOwnProperty(key) || par[key] == "") {
            par[key] = default_par[key];
        }
    }
    if (_.isEmpty(Job)) {
        throw "参数Job不存在";
    }
    var job = Job.toLowerCase();
    if (!GEN.isJobExists({ job: job })) {
        throw "料号" + job + "不存在";
    }
    if (!GEN.isJobOpen({ job: job })) {
        GEN.openJob({ job: job });
    }
    if (GEN.checkInout({ job: job, mode: "test" }) != 0 && mode == "aimdfm") {
        throw "the job check";
    }
    GEN.checkInout({ job: job, mode: "out" });
    var matrix = GEN.getMatrix({ job: job });
    var DrillLayer = Object.keys(matrix).reduce(function (a, b) {
        if (matrix[b].context == "board" && matrix[b].layer_type == 'drill') {
            a.push(b);
        }
        return a;
    }, []);
    // step过滤
    var steplist = GEN.getStepList({ job: job });
    steplist = steplist.filter(function (v) {
        var tmpreg = new RegExp(par.step_filter, "ig");
        return tmpreg.test(v);
    });
    if (steplist.length == 0 && par.step2) {
		steplist = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
    var jtg_special_tolerance_hole_diameter_final = IKM.get_jobinfo({ jobid: JobId, jobinfo: "jtg_special_tolerance_hole_diameter_final" });
    var jtg_pecial_tolerance_hole_diameter_drill = IKM.get_jobinfo({ jobid: JobId, jobinfo: "jtg_pecial_tolerance_hole_diameter_drill" });
    var jtg_special_hole_final1 = IKM.get_jobinfo({ jobid: JobId, jobinfo: "jtg_special_hole_final1" });
    var jtg_special_hole_drl1 = IKM.get_jobinfo({ jobid: JobId, jobinfo: "jtg_special_hole_drl1" });
    var jtg_special_hole_final2 = IKM.get_jobinfo({ jobid: JobId, jobinfo: "jtg_special_hole_final2" });
    var jtg_special_hole_drl2 = IKM.get_jobinfo({ jobid: JobId, jobinfo: "jtg_special_hole_drl2" });
    var tolerance = [
        {
            final: jtg_special_tolerance_hole_diameter_final,
            drl: jtg_pecial_tolerance_hole_diameter_drill
        },
        {
            final: jtg_special_hole_final1,
            drl: jtg_special_hole_drl1
        },
        {
            final: jtg_special_hole_final2,
            drl: jtg_special_hole_drl2
        }
    ];
    tolerance.forEach(function (item) {
        if (item.final) {
            item.final = parseFloat(item.final) * 1000;
            item.drl = parseFloat(item.drl) * 1000;
        }
    });
    tolerance = tolerance.filter(function(v){return v.drl})
    
    steplist.forEach(function (step) {
        GEN.openStep({ job: job, name: step });
        //料号初始化
        GEN.clearLayers(); //清除层显示
        GEN.affectedLayer({ mode: 'all', affected: 'no' }); //设置影响层全部不影响
        //操作模式初始化
        GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
        GEN.units({ type: par.units }); //单位初始化
        GEN.zoomHome(); //窗口显示回到原始位置
        // 此处只有一个dril，但是还是要做成循环，这样更通用
        DrillLayer.forEach(function (drill_layer) {
            var tmp_drl = drill_layer + "_tmp";
            // 显示finish size
            if (GEN.isLayerExists({ job: job, layer: tmp_drl })) {
                GEN.deleteLayer({ job: job, layer: [tmp_drl] });
            }
            GEN.matrixAddLayer({ job: job, layer: tmp_drl, type: "drill" });
            GEN.workLayer({ name: drill_layer, display_number: 2, clear_before: 'yes' });
            GEN.selMoveOther({ target_layer: tmp_drl, invert: 'no', dx: 0, dy: 0, size: 0 });
            GEN.workLayer({ name: tmp_drl, display_number: 2, clear_before: 'yes' });
            GEN.selMoveOther({ target_layer: drill_layer, invert: 'no', dx: 0, dy: 0, size: 0 });
            GEN.workLayer({ name: drill_layer, display_number: 2, clear_before: 'yes' });
            GEN.deleteLayer({ job: job, layer: [tmp_drl] });
			// 分离出 pth  npth  via

			setTool({
				job: job,
				step: step,
				layer: drill_layer,
				units: "mm",
				callback: function (toolinfo) {
					for (var key in toolinfo) {
						var info = toolinfo[key];
						if ( info.type == "plated" ) {
                            // 对drill_size取整
                            if (/H|L/ig.test(surfaceValue)) {
                                if (info.drill_size <= 1900) {
                                    info.drill_size = Number(info.finish_size) + 150;
                                    info.drill_size = Math.floor(info.drill_size / 50) * 50;
                                }
                                else {
                                    info.drill_size = Number(info.finish_size) + 150;
                                    info.drill_size = Math.round(info.drill_size / 50) * 50;
                                }
                            } else {
                                info.drill_size = Number(info.finish_size) + 100;
                                info.drill_size = Math.round(info.drill_size / 50) * 50;
                            }
						} else if (info.type == "non_plated" || info.type == "via") {
                            info.drill_size = Number(info.finish_size)
                            info.drill_size = Math.round(info.drill_size / 50) * 50;
                        }
					}
				}
			});

            //var pth = drill_layer + "_pth";
            //var npth = drill_layer + "_npth";
            //var via = drill_layer + "_via";
            //var tmp_layers = [pth, npth, via];
            //tmp_layers.forEach(function (l) {
            //    if (GEN.isLayerExists({ job: job, layer: l })) {
            //        GEN.deleteLayer({ job: job, layer: l });
            //    }
            //    GEN.matrixAddLayer({job:job,layer:l,type:'drill'})
            //});
            //GEN.selectByFilter({ attribute: [{ attribute: '.drill', option: 'plated' }] });
            //if (GEN.getSelectCount() > 0) {
            //    GEN.selMoveOther({ target_layer: pth, invert: 'no', dx: 0, dy: 0, size: 0 });
            //}
            //GEN.selectByFilter({ attribute: [{ attribute: '.drill', option: 'plated' }] });
            //GEN.selectByFilter({ attribute: [{ attribute: '.drill', option: 'non_plated' }] });
            //GEN.selectByFilter({ attribute: [{ attribute: '.drill', option: 'via' }] });
            //GEN.selReverse()
            //if (GEN.getSelectCount() > 0) {
            //    GEN.selMoveOther({ target_layer: pth, invert: 'no', dx: 0, dy: 0, size: 0 });
            //}
//
            //GEN.selectByFilter({ attribute: [{ attribute: '.drill', option: 'non_plated' }] });
            //if (GEN.getSelectCount() > 0) {
            //    GEN.selMoveOther({ target_layer: npth, invert: 'no', dx: 0, dy: 0, size: 0 });
            //}
            //GEN.selectByFilter({ attribute: [{ attribute: '.drill', option: 'via' }] });
            //if (GEN.getSelectCount() > 0) {
            //    GEN.selMoveOther({ target_layer: via, invert: 'no', dx: 0, dy: 0, size: 0 });
            //}
            //// 处理 npth  不放大 直接取整
            //if (GEN.isLayerExists({ job: job, layer: npth })) {
            //    GEN.workLayer({ name: npth, display_number: 2, clear_before: 'yes' });
            //    myround({ job: job, layer: npth, compensate: 0, step: step });
            //    GEN.selMoveOther({ target_layer: drill_layer, invert: 'no', dx: 0, dy: 0, size: 0 });
            //    GEN.deleteLayer({ job: job, layer: [npth] });
            //}
            //// 处理 pth  
            //if (GEN.isLayerExists({ job: job, layer: pth })) {
            //    GEN.workLayer({ name: pth, display_number: 2, clear_before: 'yes' });
            //    myround({ job: job, layer: pth, compensate: 150, step: step });
            //    GEN.selMoveOther({ target_layer: drill_layer, invert: 'no', dx: 0, dy: 0, size: 0 });
            //    GEN.deleteLayer({ job: job, layer: [pth] });
            //}
            //// via 
            //if (GEN.isLayerExists({ job: job, layer: via })) {
            //    GEN.workLayer({ name: via, display_number: 2, clear_before: 'yes' });
            //    GEN.selMoveOther({ target_layer: drill_layer, invert: 'no', dx: 0, dy: 0, size: 0 });
            //    GEN.deleteLayer({ job: job, layer: [via] });
            //}
            if (tolerance.length > 0) {
                setTool({
                    job: job,
                    step: step,
                    layer: drill_layer,
                    units: par.units,
                    callback: function (toolinfo) {
                        for (var key in toolinfo) {
                            var info = toolinfo[key];
                            info.finish_size = Number(info.finish_size);
                            tolerance.forEach(function (item) {
                                if (Math.abs(info.finish_size - item.final) <= 1) {
                                    info.drill_size = item.drl;
                                }
                            });
                        }
                    }
                });
            }

            var syms = GEN.getLayerSymsHist({job:Job,step:step,layer:drill_layer,units:'mm'})
            var tmpdrls = Object.keys(syms).filter(function(v){return (v.slice(1) -0) < 350 })
            if (/H|L/ig.test(surfaceValue) && /[CEGHL]/ig.test(jtg_through_hole_treatment) && tmpdrls.length > 0) { 
                IKM.msg("请注意喷锡开窗孔 ≥ 350")
            }
            
        });
        // GEN.closeStep();
    });

  

    // 保存 
    if (/yes/ig.test(par.auto_save)) {
        GEN.checkInout({ job: job, mode: "out" }); // 结束保存料号 关闭料号
        GEN.saveJob({ job: job });
        GEN.checkInout({ job: job, mode: "in" });
        GEN.closeJob({ job: job });
    }
    else {
        GEN.checkInout({ job: job, mode: "in" });
    }
    if (mode === "aimdfm") {
        $.QDfm.updateRow({
            table: "pdm_aimdfm_task",
            data: {
                progress: 33.33
            },
            where: { id: $.task_id }
        });
        if (GEN.hasError()) {
            Status = 'error';
            resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
            return {
                status: Status,
                result_data: resultData
            };
        }
        else {
            resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
            return {
                status: Status,
                result_data: resultData
            };
        }
    }
    else {
        return "Done";
    }
}
catch (e) {
    IKM.msg(_.join(GEN.STATUS, "\n"));
    IKM.msg(e);
    Status = 'error';
    resultData.push({ type: "error", title: "脚本执行出错!", detail: [{ desc: _.toString(e) }] });
    return (mode === "aimdfm") ? { status: Status, result_data: resultData } : "Error";
}
function setTool(props) {
    var units = props.units;
    GEN.units({ type: "mm" });
    var job = props.job;
    var step = props.step;
    var layer = props.layer;
    var tool_info = GEN.getTool({ job: job, step: step, layer: layer, units: "mm" });
    // 操作tool_info
    props.callback(tool_info);
    GEN.COM("tools_show,layer=" + layer);
    GEN.COM("tools_tab_reset");
    var typehash = {
        non_plated: "nplate",
        plated: "plate",
        via: "via",
        laser: "via"
    };
    Object.keys(tool_info).forEach(function (key) {
        var item = tool_info[key];
        if (item.shape == "hole") {
            GEN.COM("tools_tab_add,num=" + key
                + ",shape=" + item.shape + ",type=" + typehash[item.type] + ",min_tol=" + item.min_tol +
                ",max_tol=" + item.max_tol + ",bit=,finish_size=" + item.finish_size +
                ",drill_size=" + item.drill_size + ",combined=yes,orig_size=0");
        }
        else if (item.shape == "slot") {
            GEN.COM("tools_tab_add,num=" + key + ",shape=slot,type=" + typehash[item.type] + ",min_tol=" + item.min_tol + ",max_tol=" + item.max_tol + ",finish_size=" + item.finish_size +
                ",bit=,drill_size=" + item.drill_size + ",slot_len=" + item.slot_len);
        }
    });
    GEN.COM("tools_set,layer=" + layer + ",slots=by_length");
    GEN.units({ type: units });
}
function myround(props) {
    var job = props.job;
    var layer = props.layer;
    var step = props.step;
    var compensate = props.compensate;
    setTool({
        job: job,
        step: step,
        layer: layer,
        units: "mm",
        callback: function (toolinfo) {
            for (var key in toolinfo) {
                var info = toolinfo[key];
                info.drill_size = Number(info.drill_size) + compensate;
                // 对drill_size取整
                if (/H|L/ig.test(surfaceValue)) {
                    if (info.max_tol == "75" && info.min_tol == "75") {
                        if (info.drill_size <= 1900) {
                            info.drill_size = Math.floor(info.drill_size / 50) * 50;
                        }
                        else {
                            info.drill_size = Math.round(info.drill_size / 50) * 50;
                        }
                    } else {
                        info.drill_size = Math.round(info.drill_size / 50) * 50;
                    }
                } else {
                    info.drill_size = Math.round(info.drill_size / 50) * 50;
                }
            }
        }
    });
}
